package com.abaaba.project2.service.serviceImpl;

import com.abaaba.project2.bean.Admin;
import com.abaaba.project2.bean.AdminExample;
import com.abaaba.project2.bean.bo.AdminBo;
import com.abaaba.project2.bean.vo.AdminInfoVo;
import com.abaaba.project2.mapper.AdminMapper;
import com.abaaba.project2.mapper.PermissionMapper;
import com.abaaba.project2.mapper.RoleMapper;
import com.abaaba.project2.service.AdminAuthService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminAuthAuthServiceImpl implements AdminAuthService {

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    RoleMapper roleMapper;

    @Override
    public Integer Login(AdminBo adminBo) {

        //Bo拆解Pojo
        Admin admin = new Admin();
        admin.setUsername(adminBo.getUsername());
        admin.setPassword(adminBo.getPassword());

        //Pojo封装Example
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andUsernameEqualTo(admin.getUsername()).andPasswordEqualTo(admin.getPassword());

        //调用Dao层
        List<Admin> admins = adminMapper.selectByExample(adminExample);

        return admins.size();
    }

    @Override
    public AdminInfoVo getAdminInfo(String username) {

        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        criteria.andUsernameEqualTo(username);

        List<Admin> admins = adminMapper.selectByExample(adminExample);
        Integer[] roleIds = admins.get(0).getRoleIds();

        List<String> roles = new ArrayList<>();
        List<String> perms = new ArrayList<>();
        for (Integer roleId : roleIds) {
            List<String> permissions = permissionMapper.selectPermissionsByRoleId(roleId);
            String roleName = roleMapper.selectNameById(roleId);
            roles.add(roleName);
            if(permissions.contains("*"))
            {
                perms.add("*");
            }
            else
            {
                for (String permission : permissions) {
                    String api = permissionMapper.selectApiByPermission(permission);
                    perms.add(api);
                }
            }
        }

        return new AdminInfoVo(admins.get(0).getAvatar(),username,perms,roles);
    }

}
